import sys
import os
import subprocess
import re


filenames = os.listdir()
changes_filename = ''
for filename in filenames:
    if re.search(r'.*\.changes', filename):
        changes_filename = filename
print(changes_filename)
line_sha1 = 0
line_sha256 = 0
line_md5 = 0
line_md5_end = 0
with open(changes_filename) as changes_file:
    lines = changes_file.readlines()
    i = 0
    for line in lines:
        if re.search(r"Checksums-Sha1", line):
            line_sha1 = i
        if re.search(r"Checksums-Sha256", line):
            line_sha256 = i
        if re.search(r"Files", line):
            line_md5 = i
        if re.search(r' \S* \d* \S* \S* \S*', line):
            line_md5_end = i

        i += 1
line_md5_end += 1

for i in range(line_sha1+1 , line_sha256):
    text_list = lines[i].split()
    result = subprocess.run(['sha1sum', text_list[2]], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    if result.returncode != 0:
        raise Exception(f"No file{text_list[2]}")
    text = result.stdout.strip('\n')
    sha1 = text.split()[0]
    text_list[0] = sha1

    text_list[1] = str(os.path.getsize(text_list[2]))

    lines[i] = " " + " ".join(text_list) + '\n'

for i in range(line_sha256+1, line_md5):
    text_list = lines[i].split()
    result = subprocess.run(['sha256sum', text_list[2]], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    if result.returncode != 0:
        raise Exception(f"No file{text_list[2]}")
    text = result.stdout.strip('\n')
    sha256 = text.split()[0]
    text_list[0] = sha256

    text_list[1] = str(os.path.getsize(text_list[2]))

    lines[i] = " " + " ".join(text_list) + '\n'

for i in range(line_md5 +1, line_md5_end):
    text_list = lines[i].split()
    result = subprocess.run(['md5sum', text_list[4]], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    if result.returncode != 0:
        raise Exception(f"No file{text_list[4]}")
    text = result.stdout.strip('\n')
    md5 = text.split()[0]
    text_list[0] = md5

    text_list[1] = str(os.path.getsize(text_list[4]))

    lines[i] = " " + " ".join(text_list) + '\n'

with open(changes_filename, 'w') as changes_file:
    changes_file.writelines(lines)
